package org.coast.mvc.logging;

import org.coast.mvc.util.datetime.DateTimeUtil;

/**
 * default formatter  https://www.cnblogs.com/sivkun/p/7890547.html
 */
public class DefaultLogFormatter implements LogFormatter {


    @Override
    public String format(LogRecord logRecord) {
        StringBuilder sb = new StringBuilder();
        sb.append(DateTimeUtil.getNowString());
        Thread thread = Thread.currentThread();
        sb.append(" Thread ").append(logRecord.getThreadName()).append("[").append(logRecord.getThreadId()).append("]");
        sb.append(getStack());
        String color = "\33[34;3m";
        sb.append(color);
        sb.append(logRecord.getMessage());
        sb.append("\n");
        return sb.toString();
    }

    private String getStack() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        String className = "";
        String methodName = "";
        int lineNumber = 0;
        for (StackTraceElement stackTraceElement : stackTrace) {
            className = stackTraceElement.getClassName();
            methodName = stackTraceElement.getMethodName();
            lineNumber = stackTraceElement.getLineNumber();
            if (!"org.coast.mvc.logging.Logger".equals(className)) {
                break;
            }
        }
        return  " "+methodName + "[" + lineNumber+"] :";
    }
}
